//
//  KindViewController.m
//  EarnBao
//
//  Created by iMac on 15/4/16.
//  Copyright (c) 2015年 杭州赚宝科技有限公司. All rights reserved.
//

#import "KindViewController.h"
#import "KindCollectionViewCell.h"
#import "SingleKindViewController.h"
#import "Kind.h"
#import "EarnBao-API.h"
#import "Reachability.h"
#import "MBProgressHUD.h"
#import "AFNetworking.h"

@interface KindViewController ()

@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) Reachability *whole_conn;
@property (nonatomic, retain) MBProgressHUD *hud;
@property (nonatomic ,retain) NSMutableArray *waterfallArray;

@end

@implementation KindViewController

//销毁通知
- (void)dealloc
{
    [self.whole_conn stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//构建子视图
- (void)setSubViews
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.bounds.size.width/6, self.view.bounds.size.width/4);
    flowLayout.sectionInset = UIEdgeInsetsMake(self.view.bounds.size.width/24, self.view.bounds.size.width/24, self.view.bounds.size.width/24, self.view.bounds.size.width/24);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:[[UIScreen mainScreen] bounds] collectionViewLayout:flowLayout];
    _collectionView.delegate = self;  //设置代理
    _collectionView.dataSource = self;  //设置数据源
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_collectionView];
}

//数据加载完成之前显示的菊花圈
- (void)setProgressHud
{
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [_hud show:YES];
}

//视图加载完成
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"所有分类";
    
    //调用构建子视图的方法
    [self setSubViews];
    
    
    //注册一个通知用来实时监测网络状态的改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
    //创建一个全局的网络对象
    self.whole_conn = [Reachability reachabilityForInternetConnection];
    //开启通知
    [self.whole_conn startNotifier];
    
    
    [self networkStateChange];  //调用网络状态改变的方法
    
    [self getDataOfWaterfall];
}

#pragma mark ---实时监测网络状态的改变(一切数据请求和数据显示的相关处理均以网络状态的不同为基准进行！)---

//网络状态改变
- (void)networkStateChange
{
    [self checkNetworkState];
}

//检查网络状态
- (void)checkNetworkState
{
    //1.创建wifi网络对象
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    
    //2.创建手机网络对象(2G/3G/4G，也就是平时常说的手机流量)
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
    //3.判断当前app的网络连接状态，通常分为以下三种情况：
    
    //有wifi连接(包括两种情况：1.只有wifi  2.手机网络和wifi同时存在，此时wifi会自动替换掉手机网络)
    if ([wifi currentReachabilityStatus] != NotReachable) {
        
        [self setProgressHud];
        [self getDataOfWaterfall];
        [_hud hide:YES];
    }
    
    //只有手机网络
    if ([conn currentReachabilityStatus] != NotReachable && [wifi currentReachabilityStatus] == NotReachable) {
        
        [self setProgressHud];
        [self getDataOfWaterfall];
        [_hud hide:YES];
    }
}

- (void)getDataOfWaterfall
{
    //app版本号
    NSDictionary *inforDic = [[NSBundle mainBundle] infoDictionary];
    NSString *app_version = inforDic[@"CFBundleShortVersionString"];
    
    //初始化将要上传到服务器的的数据字典
    NSDictionary *parameters = @{@"app_version": app_version};
    
    //初始化请求对象
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //GET请求(也可以用POST请求)
    [manager GET:kHomePage_FocusHotAllKinds parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
         __block KindViewController *kindVC = self;
         self.waterfallArray = [[NSMutableArray alloc] initWithCapacity:0];
         NSMutableArray *allKinds_urlArray = [[NSMutableArray alloc] initWithCapacity:0];  //所有分类的url字符串数组
         NSMutableDictionary *sourceDictionary = responseObject[@"classify"];
         NSMutableArray *listArray = sourceDictionary[@"navi"];
         
         for (NSDictionary *dic in listArray) {
             
             Kind *kind = [[Kind alloc] init];
             [kind setValuesForKeysWithDictionary:dic];
             [self.waterfallArray addObject:kind];
             
             //转换数据格式(将汉字转化成url类型)
             NSString *encodedString = [kind.name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
             NSString *urlString = [NSString stringWithFormat:@"%@&classify=%@",kHomePage_ProductList,encodedString];
             [allKinds_urlArray addObject:urlString];
         }
         [kindVC.collectionView reloadData];  //重新加载数据(加上此句可以加速数据加载速度！)
        
        //将url保存到沙盒的Documents文件夹的singleKind_url.plist文件中，便于详情页取url
        
        //1.获得沙盒的根目录
        NSString *home = NSHomeDirectory();
        
        //2.获取Documents文件夹的路径
        NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
        
        //3.新建自定义文件的路径
        NSString *filepath = [docPath stringByAppendingPathComponent:@"singleKind_url.plist"];
        
        //4.写入自定义文件
        [allKinds_urlArray writeToFile:filepath atomically:YES];
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
            NSLog(@"服务器出错了！相关错误信息是:%@",error);
    }];
}

#pragma mark --- collectionView的代理方法 ---

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.waterfallArray count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    [collectionView registerClass:[KindCollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
    KindCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    Kind *kind = self.waterfallArray[indexPath.row];
    cell.kind = kind;
    [_hud hide:YES];  //数据加载完成便将菊花圈隐藏

    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    //1.获得沙盒根路径
    NSString *home = NSHomeDirectory();
    
    //2.document路径
    NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
    
    //3.文件路径
    NSString *filepath = [docPath stringByAppendingPathComponent:@"singleKind_url.plist"];
    
    //4.读取出url字符串数组
    NSArray *dataArray = [NSArray arrayWithContentsOfFile:filepath];
    
    SingleKindViewController *singleKindVC = [[SingleKindViewController alloc] init];
    singleKindVC.urlString = dataArray[indexPath.row];
    
    Kind *kind = self.waterfallArray[indexPath.row];
    singleKindVC.titleString = kind.name;
    
    [self.navigationController pushViewController:singleKindVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
